<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue</title>
  <script src="./js/vue.js"></script>
</head>

<body>
  <div id="app">
    <button @click="add">购车购加数据</button>
    <ul>
      <li v-for="item,index in cartList" :key="item.id">
        <span>{{item.name}}</span>
        <span>{{item.price}}</span>
        <span>
          {{item.num}}
          <button @click="item.num++">+++</button>
        </span>
        <span>{{item.total}}</span>
      </li>
    </ul>
    <h1>合计:{{totalPrice}}</h1>
  </div>

  <script>

    new Vue({
      el: '#app',
      data: {
        carts: [
          { id: 1, name: '小米9', price: 1, num: 1 },
          { id: 2, name: '小米10', price: 2, num: 2 },
          { id: 3, name: '小米11', price: 3, num: 3 },
        ]
      },
      methods: {
        add() {
          this.carts.push({ id: Date.now(), name: '小米11', price: 1, num: 1 })
        }
      },
      computed: {
        cartList() {
          /* return this.carts.map(item => ({
            ...item,
            total: item.price * item.num
          })) */
          return this.carts.map(item => {
            // xxx
            return {
              ...item,
              total: item.price * item.num
            }
          })
        },
        totalPrice() {
          // reduce聚合运算所用,它的性能高 reduce 高阶函数 => 1.它函数当参数 2.函数当返回值
          return this.carts.reduce((p, c) => {
            p += c.price * c.num
            return p
          }, 0)
        }
      }
    })
  </script>
</body>

</html>